/* -*- c++ -*- */
/*
 * Copyright 2004,2010 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

/*
 * config.h is generated by configure.  It contains the results
 * of probing for features, options etc.  It should be the first
 * file included in your .cc file.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <howto_spectrum_sensing_cf.h>
#include <gr_io_signature.h>
#include <math.h>
#include <stdio.h>

/*
 * Create a new instance of howto_square_ff and return
 * a boost shared_ptr.  This is effectively the public constructor.
 */
howto_spectrum_sensing_cf_sptr howto_make_spectrum_sensing_cf(float sample_rate, int ninput_samples, int samples_per_band, float pfd, float pfa, float tcme, bool output_far, bool debug_stats, int band_location, float useless_band, bool debug_histogram, int decimation)
{
  return gnuradio::get_initial_sptr(new howto_spectrum_sensing_cf (sample_rate, ninput_samples, samples_per_band, pfd, pfa, tcme, output_far, debug_stats, band_location, useless_band, debug_histogram, decimation));
}

/*
 * Specify constraints on number of input and output streams.
 * This info is used to construct the input and output signatures
 * (2nd & 3rd args to gr_block's constructor).  The input and
 * output signatures are used by the runtime system to
 * check that a valid number and type of inputs and outputs
 * are connected to this block.  In this case, we accept
 * only 1 input and 1 output.
 */
static const int MIN_IN = 1;	// mininum number of input streams
static const int MAX_IN = 1;	// maximum number of input streams
static const int MIN_OUT = 1;	// minimum number of output streams
static const int MAX_OUT = 1;	// maximum number of output streams

/*
 * The private constructor
 */
howto_spectrum_sensing_cf::howto_spectrum_sensing_cf (float sample_rate, int ninput_samples, int samples_per_band, float pfd, float pfa, float tcme, bool output_far, bool debug_stats, int band_location, float useless_band, bool debug_histogram, int decimation) 
      : gr_sync_decimator ("spectrum_sensing_cf",
	   gr_make_io_signature (MIN_IN, MAX_IN, ninput_samples*sizeof (gr_complex)),
	   gr_make_io_signature (MIN_OUT, MAX_OUT, sizeof (float)),
      decimation),
	   d_sample_rate(sample_rate),
	   d_ninput_samples(ninput_samples),
 	   d_samples_per_band(samples_per_band),
	   d_pfd(pfd),
  	   d_pfa(pfa),
	   d_tcme(tcme),
	   d_output_far(output_far),
	   d_debug_stats(debug_stats),
	   d_band_location(band_location),
	   d_useless_band(useless_band),
      d_debug_histogram(debug_histogram),
      d_nconsecutive_frames_to_check(3),
      d_nframes_to_average(4)
{	
   float delta_f = d_sample_rate/d_ninput_samples;
	d_useless_segment = (int)ceil(d_useless_band/delta_f);
	d_usefull_samples = d_ninput_samples - 6*d_useless_segment;
	d_nsub_bands = (int)floor(d_usefull_samples/d_samples_per_band);
   avg_noise = new gr_complex[d_ninput_samples];
	segment = new float[d_nsub_bands];
	sorted_segment = new float[d_nsub_bands];   

	memset(segment,0,d_nsub_bands*sizeof(float));
	memset(sorted_segment,0,d_nsub_bands*sizeof(float));

   if(d_output_far && d_debug_histogram) {
      fa_histogram = new int[d_nsub_bands];
      memset(fa_histogram,0,d_nsub_bands*sizeof(int));
   }

   if(d_debug_stats) {
	   printf("Useless band: %f\n",d_useless_band);
	   printf("Delta Frequency: %f\n",delta_f);
	   printf("Useless segment size: %d\n",d_useless_segment);
	   printf("Usefull segment size: %d\n",d_usefull_samples);
	   printf("Number of subbands: %d\n",d_nsub_bands);
   }

   memset(avg_noise,0,ninput_samples*sizeof(gr_complex));

   d_decimation = d_nconsecutive_frames_to_check*d_nframes_to_average;
}

/*
 * Our virtual destructor.
 */
howto_spectrum_sensing_cf::~howto_spectrum_sensing_cf ()
{
	delete[] segment;
	delete[] sorted_segment;
   delete[] avg_noise;
}

int
howto_spectrum_sensing_cf::work (int noutput_items,
			       gr_vector_const_void_star &input_items,
			       gr_vector_void_star &output_items)
{
   const gr_complex *in = (const gr_complex *) input_items[0];
   float *out = (float *) output_items[0];
	
   float zref, alpha, false_alarm_rate, correct_detection_rate;
   int n_zref_segs = 0, nOfTimesToCheck = d_decimation/d_average;

   for(int k = 0; k < noutput_items; k++) {
      false_alarm_rate = 0.0;
      correct_detection_rate = 0.0;
      for(int j = 0; j < nOfTimesToCheck; j++) {
         average(in, k, j);
         segment_averaged_spectrum();
	      sort_energy();
	      zref = calculate_noise_reference(&n_zref_segs);
	      alpha = calculate_scale_factor(n_zref_segs);
	      if(d_output_far) {
		      false_alarm_rate += calculate_false_alarm_rate(alpha, zref, n_zref_segs);
	      } else {
            correct_detection_rate += calculate_primary_user_detection_rate(alpha, zref, n_zref_segs);
	      }
      }
      if(d_output_far) {
         out[k] = false_alarm_rate/nOfTimesToCheck;
      } else {
         out[k] = correct_detection_rate/nOfTimesToCheck;
      }
   }

  // Tell runtime system how many output items we produced.
  return noutput_items;
}

/* Segment the spectrum into blocks with the sum of the energies.*/
void howto_spectrum_sensing_cf::average_and_segment_spectrum(const gr_complex *in, int output_item, int frame_group) {
	int pos = 0;
   gr_complex avg_value;
   const gr_complex *my_in = in + output_item*d_decimation*d_ninput_samples + frame_group*d_nframes_to_average*d_ninput_samples;


      



	for(int i=0;i<d_nsub_bands;i++) {
		segment[i] = 0.0;
		for(int k=0;k<d_samples_per_band;k++) {
			if((i*d_samples_per_band + k + d_useless_segment) <= (d_ninput_samples/2 - 2*d_useless_segment)) {
				pos = output_item*d_ninput_samples + d_useless_segment + i*d_samples_per_band + k;
				//printf("i: %d - k: %d - pos1: %d\n",i,k,(d_useless_segment + (i*d_samples_per_band) + k));

            avg_value = gr_complex(0.0,0.0);
            for(int v = 0; v < d_nframes_to_average; v++) {
               avg_value = avg_value + my_in[pos + v*d_ninput_samples];
            }
            avg_value = (avg_value)/(float)d_nframes_to_average;
				segment[i] = segment[i] + pow(abs(avg_value),2);





			} else if((i*d_samples_per_band + k + 5*d_useless_segment) > (d_ninput_samples/2 + 2*d_useless_segment) && (i*d_samples_per_band + k + 5*d_useless_segment) < (d_ninput_samples - d_useless_segment)) {
				pos = output_item*d_ninput_samples + i*d_samples_per_band + k + 5*d_useless_segment;
				//printf("i: %d - k: %d - pos2: %d\n",i,k,(i*d_samples_per_band + k + 5*d_useless_segment));
				segment[i] = segment[i] + pow(abs(in[pos]),2);
			} else {
				printf("Error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
			}
		}
		sorted_segment[i] = segment[i];
	}
}

void howto_spectrum_sensing_cf::average(const gr_complex *in, int output_item, int segment_group) {
   const gr_complex *my_in = in + output_item*d_decimation*d_ninput_samples + segment_group*d_average*d_ninput_samples;

   for(int i = 0; i < d_ninput_samples; i++) {
      avg_noise[i] = gr_complex(0.0, 0.0);
      for(int k = 0; k < d_average; k++) {
         avg_noise[i] = avg_noise[i] + my_in[i + k*d_ninput_samples];
      }
      avg_noise[i] = (avg_noise[i])/(float)d_average;
   }
}

/* Segment the averaged spectrum into blocks with the sum of the energies.*/
void howto_spectrum_sensing_cf::segment_averaged_spectrum() {
	int pos = 0;

	for(int i=0;i<d_nsub_bands;i++) {
		segment[i] = 0.0;
		for(int k=0;k<d_samples_per_band;k++) {
			if((i*d_samples_per_band + k + d_useless_segment) <= (d_ninput_samples/2 - 2*d_useless_segment)) {
				pos = d_useless_segment + i*d_samples_per_band + k;
				//printf("i: %d - k: %d - pos1: %d\n",i,k,(d_useless_segment + (i*d_samples_per_band) + k));
				segment[i] = segment[i] + pow(abs(avg_noise[pos]),2);
			} else if((i*d_samples_per_band + k + 5*d_useless_segment) > (d_ninput_samples/2 + 2*d_useless_segment) && (i*d_samples_per_band + k + 5*d_useless_segment) < (d_ninput_samples - d_useless_segment)) {
				pos = i*d_samples_per_band + k + 5*d_useless_segment;
				//printf("i: %d - k: %d - pos2: %d\n",i,k,(i*d_samples_per_band + k + 5*d_useless_segment));
				segment[i] = segment[i] + pow(abs(avg_noise[pos]),2);
			} else {
				printf("Error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
			}
		}
		sorted_segment[i] = segment[i];
	}
}

/* Segment the spectrum into blocks with the sum of the energies.*/
void howto_spectrum_sensing_cf::segment_spectrum(const gr_complex *in, int vector_number) {
	int pos = 0;

	for(int i=0;i<d_nsub_bands;i++) {
		segment[i] = 0.0;
		for(int k=0;k<d_samples_per_band;k++) {
			if((i*d_samples_per_band + k + d_useless_segment) <= (d_ninput_samples/2 - 2*d_useless_segment)) {
				pos = vector_number*d_ninput_samples + d_useless_segment + i*d_samples_per_band + k;
				//printf("i: %d - k: %d - pos1: %d\n",i,k,(d_useless_segment + (i*d_samples_per_band) + k));
				segment[i] = segment[i] + pow(abs(in[pos]),2);
			} else if((i*d_samples_per_band + k + 5*d_useless_segment) > (d_ninput_samples/2 + 2*d_useless_segment) && (i*d_samples_per_band + k + 5*d_useless_segment) < (d_ninput_samples - d_useless_segment)) {
				pos = vector_number*d_ninput_samples + i*d_samples_per_band + k + 5*d_useless_segment;
				//printf("i: %d - k: %d - pos2: %d\n",i,k,(i*d_samples_per_band + k + 5*d_useless_segment));
				segment[i] = segment[i] + pow(abs(in[pos]),2);
			} else {
				printf("Error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
			}
		}
		sorted_segment[i] = segment[i];
	}
}

/*This is the implementation of the algorithm proposed in reference [3]*/
bool howto_spectrum_sensing_cf::sort_energy() {
	float temp;

	//Sort Segmented PDP vector in increasing order of energy.
	for(int i=0;i<d_nsub_bands;i++) {
		for(int k=0;k<(d_nsub_bands-1);k++) {
			if(sorted_segment[k] > sorted_segment[k+1]) {
				temp = sorted_segment[k+1];
				sorted_segment[k+1] = sorted_segment[k];
				sorted_segment[k] = temp;
			}
		}
	}
	
	return true;
}

/* Algorithm used to discard samples. Indeed, it is used to find a speration between noisy samples and signal+noise samples.*/
float howto_spectrum_sensing_cf::calculate_noise_reference(int* n_zref_segs) {
	
	float limiar, energy[d_nsub_bands];
	int I = (d_nsub_bands < 20)?3:20;

	for(;I<d_nsub_bands;I++) {
		limiar = (float)(d_tcme/I);
		energy[I] = 0.0;
		for(int k=0;k<I;k++) {
			energy[I] = energy[I] + sorted_segment[k];
		}
		if(sorted_segment[I] > limiar*energy[I] || I==(d_nsub_bands-1)) {
			break;
		}
	}

	(*n_zref_segs) = I;
	return energy[I];
}

// Calculate the scale factor.
float howto_spectrum_sensing_cf::calculate_scale_factor(int x) {
	float alpha = 0.0;

	boost::math::fisher_f_distribution<> fd(2*d_samples_per_band, 2*d_samples_per_band*x);
	alpha = quantile(fd, (1-d_pfa));
	return alpha/x;
}

float howto_spectrum_sensing_cf::calculate_false_alarm_rate(float alpha, float zref, int I) {
	
	float ratio;
   int false_alarm_counter;

   false_alarm_counter = 0;
	for(int k=0;k<d_nsub_bands;k++) {
		ratio = segment[k]/zref;
		if(ratio > alpha) {
			if(d_debug_stats) printf("ratio: %f - alpha: %f - segment[%d]: %f - zref: %f - I: %d\n",ratio,alpha,k,segment[k],zref,I);
         if(d_debug_histogram) fa_histogram[k]++;
			false_alarm_counter++;
		}
	}

	return (float)false_alarm_counter/d_nsub_bands;
}

float howto_spectrum_sensing_cf::calculate_primary_user_detection_rate(float alpha, float zref, int I) {

	float ratio = 0.0, numberOfCorrectDetections = 0.0;
   int nSegsToCheck = 6;

   for(int i=0;i<=nSegsToCheck;i++) {
      ratio = segment[d_band_location-(nSegsToCheck/2)+i]/zref;
      if(ratio > alpha) {
         numberOfCorrectDetections++;
      }
      if(d_debug_stats) printf("ratio: %f - alpha: %f - segment[%d]: %f - zref: %f - I: %d\n",ratio,alpha,i,segment[i],zref,I);
   }

   return numberOfCorrectDetections/(nSegsToCheck+1);
}

/* REFERENCES

[1] Sesia, S., Baker, M., Toufik, I. - "LTE, the UMTS long term evolution: From theory to practice. Chichester", Wiley InterScience, 2009.
[2] 3GPP Technical Specification 36.213 - "Physical layer procedures (Release 10)", ww.3gpp.org.
[3] Jing Jiang, Muharemovic, Pierre Bertrand - "Random Access Preamble Detection for Long Term Evolution Wireless Networks", Patent number US 2009/0040918 A1.
[4] Fabbryccio A. C. Cardoso, Juliano João Bazzo, and Fabrício Lira Figueiredo, “Método de detecção de sinal primário para faixa de TV”, Caderno CPqD de Tecnologia.
*/

